package com.sense.cloud.coreservice.sdk.auth.utils.http.assist;

import com.sense.cloud.coreservice.sdk.auth.utils.SdkPropUtil;
import com.sense.cloud.coreservice.sdk.auth.utils.http.assist.IdleConnectionMonitorThread;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContexts;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

import javax.net.ssl.SSLContext;

public class HttpClientConnectionManagerWrapper {
  private static final Logger LOGGER = 
                 LoggerFactory.getLogger(HttpClientConnectionManagerWrapper.class);
  private static final int MAX_CONNECTION_COUNT = SdkPropUtil.getHttpConnectionPoolMax();
  private static PoolingHttpClientConnectionManager cm;
  private static IdleConnectionMonitorThread idleConnMonitor;

  private static void init() {
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslcontext, new String[] { "TLSv1", "SSLv3" }, null,
            SSLConnectionSocketFactory.getDefaultHostnameVerifier());

    Registry<ConnectionSocketFactory> socketFactoryRegistry = 
            RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslConnectionSocketFactory)
            .build();
    cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    cm.setMaxTotal(MAX_CONNECTION_COUNT);
    
    idleConnMonitor = new IdleConnectionMonitorThread(cm);
    idleConnMonitor.start();
  }
  
  private static class HttpClientConnectionManagerWrapperHolder {
    static CloseableHttpClient httpClient;
      
    static {
      init();
      httpClient = HttpClients.custom().setConnectionManager(cm).build();
    }
  }
  
  /**
   *info . 
   */
  public static void close() {
    if (HttpClientConnectionManagerWrapperHolder.httpClient != null) {
      try {
        HttpClientConnectionManagerWrapperHolder.httpClient.close();
      } catch (IOException e11) {
        LOGGER.error(e11.getMessage(), e11);
      }
    }
    if (idleConnMonitor != null) {
      idleConnMonitor.shutdown();
    }
  }
    
  public static CloseableHttpClient getHttpClient() {
    return HttpClientConnectionManagerWrapperHolder.httpClient;
  }
}
